package com.wdb007.venus.wss.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wdb007.venus.svc.facade.ProcessInstructionService;
import com.wdb007.venus.svc.facade.process.model.ProcessInstructionLogDTO;
import com.wdb007.venus.wss.channelgroup.AppChannelGroups;
import com.wdb007.venus.wss.service.WebSocketServerService;

import io.netty.channel.ChannelHandlerContext;

@Service("appService")
public class SenderToAppService implements WebSocketServerService {

	private static Logger logger = LoggerFactory.getLogger(SenderToAppService.class);
	
	@Autowired
	private ProcessInstructionService processInstructionService;
	
	@Override
	public String doService(ChannelHandlerContext ctx, String request) throws Exception {
		
		JSONObject jsonObj = JSON.parseObject(request);
		String userId = jsonObj.getString("userid");
		
		String bookgrid_code = jsonObj.getString("bookgrid_code");
		String action = jsonObj.getString("action");
		ProcessInstructionLogDTO pi = new ProcessInstructionLogDTO();
		pi.setContent(jsonObj.toJSONString());
		pi.setBookgridCode(bookgrid_code);
		pi.setUserId(Long.valueOf(userId));
		pi.setAction(action);
		processInstructionService.notifyToAPP(pi);
		
		jsonObj.remove("userid");
		logger.info("debug: 给APP用户[{}],下发内容[{}]",userId, jsonObj.toJSONString());
		AppChannelGroups.broadcast(userId, jsonObj.toString());
		return null;
	}

}
